/**
 * @(#) Receiver.java
 */

package it.unibo.iss.domotica.readingData;

import org.apache.log4j.Logger;
import it.unibo.contact.domoticaContact.ReceiverSupport;
import it.unibo.is.interfaces.IMessage;
import it.unibo.iss.domotica.converter.DomoticaJsonConverter;
import it.unibo.iss.domotica.edDomain.ConsumptionData;
import it.unibo.iss.domotica.edDomain.IImpiantoElettrico;

public class Receiver extends ReceiverSupport
{
	private IImpiantoElettrico elettrodomestici;
	private boolean stopThread;
	private DomoticaJsonConverter converter;
	// Logger
	private Logger logger = Logger.getLogger(Receiver.class);
	
	public Receiver(IImpiantoElettrico elettrodomestici) throws Exception {
		this.elettrodomestici = elettrodomestici;
		stopThread = false;
		converter = new DomoticaJsonConverter();
	}
	
	public void setStopThread(boolean stopThread) {
		this.stopThread = stopThread;
	}

	private void receiveData() {
		// 1. Ricezione segnale contenente nome elettrodomestico e consumo attuale
		// 2. registerData(edName, consume);
		try {
			// 1. Ricezione segnale contenente nome elettrodomestico e consumo attuale
			IMessage mm = hl_receiver_serve_consumptionData();
//			logger.debug("Received data " + mm.msgContent());
			String dataString = mm.msgContent();
			
			// 2. registerData(edName, consume);
//			String edName = dataString.split("=")[0];
//			double consumption = Double.valueOf(dataString.split("=")[1]);
//			registerData(edName, consumption);
			ConsumptionData data = converter.stringToConsumptionData(dataString);
			registerData(data.getEdName(), data.getConsumption());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void registerData(String edName, double consumption) {
		logger.debug("Registering data " + consumption + " for " + edName);
		
		elettrodomestici.setConsumptionEd(edName, consumption);
	}

	@Override
	public void doJob() throws Exception {
		logger.debug("Receiver started");
		
		while(!stopThread) {
			receiveData();
		}
	}	
}
